package wyx240426;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.math.*;
import java.math.BigInteger;
public class ComputerServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ComputerBean computerBean = (ComputerBean) req.getAttribute("computerBean");
        if (computerBean == null) {
            computerBean = new ComputerBean();
            req.setAttribute("computerBean", computerBean);
        }
        String num1 = req.getParameter("num1");
        String num2 = req.getParameter("num2");
        String op = req.getParameter("op");
        if (noValidInput(num1) || noValidInput(num2)) return;
        BigDecimal num1_ = new BigDecimal(num1);
        BigDecimal num2_ = new BigDecimal(num2);
        BigDecimal result = new BigDecimal(0);
        switch (op) {
            case "+":
                result = num1_.add(num2_);
                break;
            case "-":
                result = num1_.subtract(num2_);
                break;
            case "*":
                result = num1_.multiply(num2_);
                break;
            case "/":
                if (num2_.compareTo(BigDecimal.ZERO) == 0) return;
                result = num1_.divide(num2_, 2, RoundingMode.HALF_UP);
                break;
            case "%":
                BigInteger a=num1_.toBigInteger();
                BigInteger b=num2_.toBigInteger();
                result=new BigDecimal(a.mod(b));
                break;
        }
        computerBean.setNum1(num1_);
        computerBean.setNum2(num2_);
        computerBean.setOperator(op);
        computerBean.setResult(result);
        req.getRequestDispatcher("/240426/jsp/day01.jsp").forward(req, resp);
    }
    private boolean noValidInput(String input) {
        return input == null || input.isEmpty() || !input.matches("-?\\d+(\\.\\d+)?");
    }
}
